import React from 'react';
import $ from 'webpack-zepto';
import Util from '../../common/util.js';
import Config from '../../common/config.js';
import Loader from '../../common/loader.js';
import Pay from '../../common/weixin-pay.js';
import Modal from '../../common/modal.js';
import GoodsInfo from './goods-info.js';
import ShipType from './ship-type.js';
import PayType from './pay-type.js';


var data = {
    ship_type : [{ship_code : 'shunfeng', ship_conpany : '商家包邮'}, {ship_code : 'ziti', ship_conpany : '用户自提'}],
    pay_type : [{payment_way : 'cash', pay_name : '微信支付', pay_icon : 'images/weipay.png'},{payment_way : 'coin', pay_name : '余额支付', pay_icon : 'images/yuepay.png'}]
};

var scope;
var defaultAddress;
var orderResult = {};
var payData = {};
export default class OrderPay extends React.Component{

    constructor(props) {
        super(props);
        var buyGoods = Util.storage().get('toBuyGoods');
        if(!buyGoods){
            var appid = Util.getUrlParam('appid');
            window.location.href = 'index.html?appid=' + appid;
        }
        if(buyGoods.oid){
            orderResult.oid = buyGoods.oid;
        }
        document.title = '订单详情';
        scope = this;
        scope.state = {
            error : false,
            user : false,
            ship_type_index : 0,
            pay_type_index : 0,
            payment_way : data.pay_type[0].payment_way,
            ship_code : data.ship_type[0].ship_code,
            buyGoods : buyGoods
        };
    };

    componentDidMount(){
        var token = Util.storage().get(scope.props.appId);
        $.ajax({
            url : Config.path('duolu/user',['?uToken=' + token]),
            type : 'get',
            dataType : 'json',
            success : function(resp){
                if(resp.status == 200){
                    scope.setState({
                        user : resp.data
                    });
                }else if(resp.status == 401){
                    alert('用户登录失效！');
                    window.location.href = 'index.html?appid=' + scope.props.appId;
                }else {
                    scope.setState({
                        error : true
                    });
                }
            }
        });
    };

    handleShipTypeCallback(i,shipCode){
        scope.setState({
            ship_type_index : i,
            ship_code : shipCode
        });

    };

    handlePayTypeCallback(i,payCode){
        scope.setState({
            pay_type_index : i,
            payment_way : payCode
        });
    };

    handleToPay(){
        if(orderResult && orderResult.oid){
            scope.cashPay(orderResult);
        }else {
            payData.payment_way = scope.state.payment_way;
            payData.ship_code = scope.state.ship_code;
            payData.remark = scope.refs.remark.value;
            payData.address_id = defaultAddress.id;
            payData.goods = [];
            var goodsList = scope.state.buyGoods.orderGoods;
            if(goodsList && goodsList.length > 0){
                goodsList.map(function (item) {
                    var singleGoods = scope.dealOrderGoods(item);
                    if(item.yhg_goods && item.yhg_goods[0]){
                        payData.goods.push({
                            goods_id : item.yhg_goods[0].yhg_goods_id,
                            goods_num : item.yhg_goods[0].yhg_goods_num,
                            is_yhg : 'Y',
                            goods_pid : item.goods_id
                        });
                    }
                    payData.goods.push(singleGoods);
                })
            }
            scope.submitOrder(payData);
        }
    };

    submitOrder(orderData){
        var token = Util.storage().get(scope.props.appId);
        $.ajax({
            url : Config.path('duolu/order',['?uToken=' + token]),
            type : 'post',
            data : orderData,
            dataType : 'json',
            beforeSend : function(){
                Loader.start();
            },
            success : function(resp){
                if(resp.status == 200){
                    orderResult = resp.data;
                    scope.handleOrderPay(orderResult);
                }else if(resp.status == 401){
                    alert('用户登录失效！');
                    window.location.href = 'index.html?appid=' + scope.props.appId;
                }else{
                    if('coin' == payData.payment_way){
                        scope.failPayModalSet(true);
                    }else{
                        alert('提交订单失败！');
                    }
                }
                Loader.end();
            }
        })
    };

    handleOrderPay(orderResult){
        if(orderResult.isPay == true){
            var appid = Util.getUrlParam('appid');
            window.location.href = 'order.html?appid=' + appid;
            return;
        }
        if('coin' == payData.payment_way){
            scope.successPayModalSet();
            orderResult.isPay = true;
            Util.storage().remove('toBuyGoods');
            Util.storage().remove('selectAddressId');
        }else if('cash' == payData.payment_way) {
            scope.cashPay(orderResult);
        }

    };

    cashPay(orderResult){
        var oid = orderResult.oid;
        Pay.weixinPay(oid,function (res) {
            if(res.err_msg == 'get_brand_wcpay_request:ok'){
                scope.successPayModalSet();
                orderResult.isPay = true;
                Util.storage().remove('toBuyGoods');
                Util.storage().remove('selectAddressId');
            }else{
                scope.failPayModalSet(false,oid);
            }
        })
    };

    dealOrderGoods(goods){
        var singleGoods = {
            goods_id : goods.goods_id,
            goods_num : goods.goods_num
        };
        return singleGoods;
    };

    backToOrder(){
        var appid = Util.getUrlParam('appid');
        window.location.href = 'order.html?type=order&appid=' + appid;
    };

    backToHome(){
        var appid = Util.getUrlParam('appid');
        window.location.href = 'index.html?appid=' + appid;
    };

    successPayModalSet(){
        Modal.modal({
            isSuccess : true,
            header : '付款成功!',
            body : '请保持电话畅通，等待宝贝送达!',
            centerBtn : {
                text : '我的订单',
                isCallback : function () {
                    scope.backToOrder();
                }
            },
            lowerBody : false
        });
    };

    failPayModalSet(isCoin,oid){
        var setting  = {
            isSuccess : false,
            header : '付款失败!',
            body : (isCoin ? '余额支付失败，请确认余额是否充足!' : '微信支付失败!'),
            lowerBody : false,
            closeIcon : false
    };
        if(isCoin){
            setting.centerBtn = {
                text : '我的订单',
                isCallback : function () {
                    scope.backToOrder();
                }
            };
        }else{
            setting.firstBtn  = {
                text : '返回首页',
                isCallback : function () {
                        scope.backToHome();
                }
            };

            setting.secondBtn = {
                text : '重新支付',
                isCallback : function () {
                    Modal.close();
                    orderResult.oid = oid;
                }
            };
        }
        Modal.modal(setting);

    };

    render(){
        if(scope.state.error){
            return <div className="load-error">数据请求错误！</div>;

        }else {
            if(!scope.state.user){
                return (
                    <div className="load8">
                        <div class="loader"></div>
                    </div>
                );
            }else{
                if(scope.state.user.addressList.length == 0){
                    var appid = Util.getUrlParam('appid');
                    window.location.href = 'address.html?type=form&page=order&appid=' + appid;
                }else{
                    return scope.initPage();
                }
            }
        }
    };

    initPage(){
        var shipData = {
            ship_type : data.ship_type,
            ship_type_index : scope.state.ship_type_index
        };
        var payData = {
            pay_type : data.pay_type,
            pay_type_index : scope.state.pay_type_index,
            coin_amount : scope.state.user.coin
        };
        return (
            <div className="pay">
                {this.orderAddress()}
                <GoodsInfo data={scope.state.buyGoods}></GoodsInfo>
                <ShipType data={shipData} callbackShipType={scope.handleShipTypeCallback} ></ShipType>
                <PayType data={payData} callbackPayType={scope.handlePayTypeCallback}></PayType>
                {this.remark()}
                {this.footer()}
            </div>
        );
    };

    orderAddress(){
        defaultAddress = scope.getDefaultAddress();
        var appid = Util.getUrlParam('appid');
        return (
            <div className="address">
                <div>
                    <span className="icon"></span>
                    <span>{defaultAddress.contact}</span>
                    <span>{defaultAddress.tel}</span>
                </div>
                <div>
                    <span className="icon"></span>
                    <span>{defaultAddress.province + defaultAddress.city + defaultAddress.district + defaultAddress.address}</span>
                </div>
                <a className="goAddress" href={"address.html?type=list&page=order&appid=" + appid}></a>
            </div>
        );
    };

    getDefaultAddress(){
        var selectAddressId = Util.storage().get('selectAddressId');
        var addressList = scope.state.user.addressList;
        var address;
        for(var i in addressList) {
            if (selectAddressId) {
                if (selectAddressId == addressList[i].id) {
                    address = addressList[i];
                    break;
                }
            } else {
                if ('1' == addressList[i].is_default) {
                    address = addressList[i];
                    break;
                }
            }
        }
        
        if(!address){
            address = addressList[0];
        }
        return address;
    };

    remark(){
        return (
            <div className="pay-part">
                <div className="part-head">备注</div>
                <div className="type-box remark-box">
                    <input ref="remark" className="remark-info" placeholder="选填，留下需要备注的信息" />
                </div>
            </div>
        );
    };

    footer(){
        return (
            <div className="footer">
                <div className="footer-left">
                    订单金额：RMB <span className="order-total-price">{scope.state.buyGoods.totalPrice}</span>
                </div>
                <div className="footer-right" onClick={scope.handleToPay}>去支付</div>
            </div>
        )
    };
};
